package dataMigration;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;


public class Migrate 
{
	String _query;
	Statement sourceStatement; 
	Statement targetStatement;
	DBconnect sourceDB;
	DBconnect targetDB;

	ResultSet rs;
	String tablename;
	int columnCount;
	
	public void setSourceDBconnect(DBconnect sourceDB)
	{
		this.sourceDB = sourceDB;
	}
	public void setTargetDBconnect(DBconnect targetDB)
	{
		this.targetDB = targetDB;
	}
	public void setTableName(String tablename) {
		this.tablename = tablename;
	}
	public void createTeable()
	{
		
		Connection con = sourceDB.getConnect();
		
		String createQuery = "CREATE TABLE "+tablename+"(";
		sourceStatement = sourceDB.getStatement(con);
		try 
		{
			rs = sourceStatement.executeQuery("select * from "+tablename);
			rs.next();
			ResultSetMetaData rsMetaData = rs.getMetaData();
			columnCount = rsMetaData.getColumnCount();
			for(int i=1;i<=columnCount;i++)
			{
				String col = rsMetaData.getColumnName(i);
				String type = rsMetaData.getColumnTypeName(i);
				createQuery = createQuery + col + " " + type + "," ;
			}
			
			createQuery = createQuery.substring(0,createQuery.length()-1);
			createQuery = createQuery + ")";
			rs.previous();
		}
		catch (SQLException e) {
			e.printStackTrace();
		}
		
		//Create Table 
		
		con = targetDB.getConnect();
		targetStatement = targetDB.getStatement(con);
		
		try 
		{
			System.out.println(createQuery);
			targetStatement.execute(createQuery);
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		
	}
	
	public boolean inserData()
	{
		
		try 
		{
			while(rs.next())
			{
				try {
					String stmt = "insert into "+tablename+" values(";
					for (int i=1; i<= columnCount;i++)
					{
						try
						{
							String value = rs.getString(i);
							if(value.contains("\'"))
								value = value.replace("\'", "\\\'");
							if(!value.equalsIgnoreCase("null"))
								stmt =stmt + "'" + value + "'" + ",";
							else
								stmt =stmt + value + ",";
						}
						catch (Exception e) {
							stmt =stmt + null + ",";
						}
					}
					stmt = stmt.substring(0,stmt.length()-1) + ")";
					System.out.println(stmt);
					targetStatement.executeUpdate(stmt);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}
	
}
